<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Custom_View_Helper_GetLink extends Zend_View_Helper_Abstract
{

	public function getLink($label, $href, $attributes = array('class'=>'link'), $routeName = null)
	{
		$router = Zend_Controller_Front::getInstance()->getRouter();
		$link = '';
		
		if($routeName && $router->hasRoute($routeName))
		{
			$objRoute = $router->getRoute($routeName);
			$arrDefaults = $objRoute->getDefaults();
			$resource = $arrDefaults['module']."_".$arrDefaults['controller'];
			$permission = $arrDefaults['action'];
		}
		else
		{
			#assume module/controller/action in $href
			#extract module, controller and action
			$arrDefaults = explode('/', $href);
			if(count($arrDefaults) > 1)
			{
				$resource = $arrDefaults[0]."_".$arrDefaults[1];
				$permission = ($arrDefaults[2]) ? $arrDefaults[2] : 'index';
			}
			else
			{
				return $this->_constructLink($label, $attributes, $href);
			}
		}
		
		if($resource && $permission)
		{
			$hasPermission = $this->view->aclAuth->hasPermission($resource, $permission);

			if($hasPermission)
			{
				$link = $this->_constructLink($label, $attributes, $href);
			}
		}
	
		return $link;
	}

	private function _constructLink($label, $attributes, $href)
	{
		if(!strstr($href,'javascript') && !strstr($href,'#')) $href = $this->view->baseUrl($href);

		$link = '<a href="'.$href.'" ';

		foreach($attributes as $attr => $value)
		{
			$link .= $attr. '="' .$value .'"';
		}

		$link .= '>'.$label.'</a>';

		return $link;
	}
}
?>
